package com.cup.wx.micro.web;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cup.wx.micro.util.WebchatUtil;

/**
 * @Title:  微信支付模块回调
 * @author: alan.deyu.zhao
 * @date:   Jan 4, 2019
 */
@RestController
@RequestMapping("wxpay/callback")
public class WxPayCallbackApi {
	
	@RequestMapping("notify")
	public void templateMsgEventCallback(HttpServletRequest request, HttpServletResponse response) throws Exception{
		BufferedOutputStream out = null;
		try {
			String responseXml = "";
            String inputLine;
            while ((inputLine = request.getReader().readLine()) != null) {
            	responseXml = responseXml + inputLine;
            }
            request.getReader().close();
			// 
			Map<String, String> xmlToMap = WebchatUtil.xmlToMap(responseXml);
			
			// TODO 
			String resXml = "";
			if ("SUCCESS".equals(xmlToMap.get("return_code"))) {
				
                resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";
				
            } else {
            	
                resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml> ";
            }
			
			// 通知微信
			out = new BufferedOutputStream(response.getOutputStream());
			out.write(resXml.getBytes());
		    out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			out.close();
		}
	}
}
